package com.greenant.store.utils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVUser;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.activity.LoginActivity;
import com.greenant.store.bean.MyMsg;
import com.greenant.store.bean.Order;
import com.greenant.store.bean.OrderItem;
import com.greenant.store.bean.OrderStatusCode;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.view.CommonDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

public class UtilTools {
	public static void showMyToast(Context context, String text) {
		if (context == null) {
			return;
		}

		try {
			// content view
			View contentView = LayoutInflater.from(context).inflate(
					R.layout.toast, null);
			TextView tv = (TextView) contentView.findViewById(R.id.toast_text);
			tv.setText((text == null ? "" : text));

			// show toast
			Toast toast = new Toast(context);
			toast.setView(contentView);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void exit(Context context) {
		ImageLoader.getInstance().clearMemoryCache();
		AppExitManager.getInstance().appExit(context);
	}

	public static boolean isUserLogined(Context context) {
		AVUser currentUser = AVUser.getCurrentUser();
		if (currentUser != null) {
			return true;
		} else {
			Intent intent = new Intent(context, LoginActivity.class);
			context.startActivity(intent);
			return false;
		}
	}

	public static void cleanAllCache(Context context) {

		String packageName = context.getPackageName();
		FileUtils.reverseDeleteFile(context.getCacheDir());
		FileUtils.reverseDeleteFile(ImageLoader.getInstance().getDiskCache()
				.getDirectory());

	}

	/**
	 * 根据订单列表获取总支付金额
	 * 
	 * @param items
	 * @return
	 * @since 3.8
	 */
	public static double getTotalCostByOrderItems(List<OrderItem> items) {
		DecimalFormat df = new DecimalFormat("#########.##");
		double totalCost = 0;
		if (items != null && items.size() > 0) {

			for (int i = 0; i < items.size(); i++) {
				OrderItem orderItem = items.get(i);
				if (orderItem.isWeighAble()) {
					if (orderItem.getWeight() < 0.000001) {
						totalCost = 0;
						break;
					} else {
						totalCost += (orderItem.getWeight() * orderItem
								.getPrice());
					}
				} else {
					totalCost += (orderItem.getQuantity() * orderItem
							.getPrice());
				}
			}
		}

		return Double.parseDouble(df.format(totalCost));
	}

	/**
	 * 获取订单描述字段
	 * @param context
	 * @param order
	 * @return
	 */
	public static String getOrderStatusString(Context context,Order order){
		try {
			int statusCode = order.getStatusCode();
			String[] orderStatus = context.getResources().getStringArray(R.array.order_status_code);
			if (order.isPayed()) {
				if (order.getStatusCode() == OrderStatusCode.ORDER_PENDING.value()
						|| order.getStatusCode() == OrderStatusCode.ORDER_WEIGHED.value())
					return context.getString(R.string.order_status_code_1);

			}
			return orderStatus[statusCode];
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
		
	}
	/**
	 * 处理button和textview状态
	 * 
	 * @param statusCode
	 * @param statuss
	 * @param close
	 * @param payContinue
	 * @param order_detail_status
	 */

	public static void processOrderStatus(Button close, Button payContinue,
			TextView order_detail_status, Context context, Order order) {
		int statusCode = order.getStatusCode();
		String[] orderStatus = context.getResources().getStringArray(
				R.array.order_status_code);
		close.setVisibility(View.VISIBLE);
		payContinue.setVisibility(View.VISIBLE);
		// 初始数据为
		// close.setText(R.string.button_order_return);

		try {
			order_detail_status.setText(orderStatus[statusCode]);
		} catch (Exception e) {
			e.printStackTrace();
		}

		switch (OrderStatusCode.values()[statusCode]) {
		case ORDER_PENDING:// 0 -待发货
			close.setText(R.string.button_order_hurry);
			close.setVisibility(View.GONE);
			break;
		case ORDER_SHIPPED:// 1-已发货
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_confirm);
			close.setVisibility(View.GONE);
			break;
		case ORDER_2_STATION:// 2-已送至自提点
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_confirm);
			close.setVisibility(View.GONE);
			break;
		case ORDER_SIGNED:// 3-已签收
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_close);
			close.setVisibility(View.GONE);
			break;
		case ORDER_WAIT_FOR_PAY:// 4-待付款
			close.setVisibility(View.GONE);
			break;
		case ORDER_WAIT_FOR_SIGN:// 5-待收货
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_cancel);
			close.setVisibility(View.GONE);
			break;
		case ORDER_WEIGHED:// 9-已称重
			// 已经支付，可申请退货，关闭订单
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_cancel);
			close.setVisibility(View.GONE);
			break;
		case ORDER_REFUNDING:// 6-退款中
		case ORDER_REFUNDED:// 7-已退款
		case ORDER_FINISHED:// 8-已完成
		case ORDER_REFUND_ACCEPT: // 10-同意退款
		case ORDER_CANCELED: // 11-已取消
		case ORDER_CLOSED: // 12-已关闭
			close.setVisibility(View.GONE);
			payContinue.setVisibility(View.GONE);
			break;
		default:
			close.setVisibility(View.GONE);
			payContinue.setVisibility(View.GONE);
			break;
		}

	}


	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	public static Date parseDateStr(String formatStr, String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
		try {
			Date date = sdf.parse(dateStr);
			Log.d("CEXX",
					"CEXX ---> parseDateStr ---> hour : " + date.getHours());
			Log.d("CEXX",
					"CEXX ---> parseDateStr ---> minute : " + date.getMinutes());
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return Calendar.getInstance().getTime();
	}
	
	public static boolean getFlagStoreInfo(Application application) {
		String spName = "sp_name_have_store_info";
    	String spKeyHaveStoreInfo = "sp_key_have_store_info";
        
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        return sp.getBoolean(spKeyHaveStoreInfo, false);
    }
    
    public static void saveFlagStoreInfo(Application application, boolean haveStoreInfo) {
    	String spName = "sp_name_have_store_info";
    	String spKeyHaveStoreInfo = "sp_key_have_store_info";
        
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putBoolean(spKeyHaveStoreInfo, haveStoreInfo);
	    editor.commit();
    }
}
